<?php

namespace app\Admin\controller;

use app\Admin\model\Type;
use think\Cache;
use think\Controller;
use think\Db;
use think\Request;
use app\Admin\model\Information as InformationModel;
use think\Session;

class Information extends Controller
{
    /**
     * @return \think\response\View
     * User: Mr.zhao
     * Date: 2021/5/7 9:32
     * 展示分类列表+资讯列表展示
     */
    public  function type_list(Request $request)
    {
        //实例化redis
        $redis = Cache::store('redis')->handler();

        //获取分类id
        $id = $request->get('id');
        //获取用户id
        $user_id =  session('user');
        //获取用户收藏的资讯
        $infor_info = $redis->smembers('information_'.$user_id);
        //转化为字符串
        $infor_id = implode(',',$infor_info);
        //判断分类id是否存在
        if ($id == ''){
            $id = 1;
        }
        //查询分类下的所有资讯
        $data = Collection(InformationModel::where('t_id',$id)->limit(3)->select())->toArray();
        //查询所有分类
        $type_info = Collection(Type::all())->toArray();
        //使用redis存储分类
        Cache::set($id,$type_info);

        return view('Information/type-list',compact('type_info','data','infor_id'));
    }

    /**
     * @param Request $request
     * User: Mr.zhao
     * Date: 2021/5/7 10:04
     * 文章详情页
     */
    public  function information_detail(Request $request)
    {
        //实例化redis
        $redis = Cache::store('redis')->handler();

        //获取资讯id
        $id = $request->get('id');

        if ($redis->exists('infor_'.$id)){
            $redis->get('infor_'.$id);
        }else{
            $redis->set('infor_'.$id,0);
        }
        $read_num = $redis->incr('infor_'.$id,1);

        //上一篇
        $prev = InformationModel::where('id','<',$id)->order('id','desc')->limit(1)->find();

        //下一篇
        $next = InformationModel::where('id','>',$id)->order('id','asc')->limit(1)->find();

        //查询出一条资讯信息
        $one_data = InformationModel::find($id);

        //渲染视图
        return view('Information/detail',compact('one_data','read_num','prev','next'));

    }

    /**
     * @param Request $request
     * User: Mr.zhao
     * Date: 2021/5/7 11:14
     * 收藏功能实现
     */
    public  function love(Request $request)
    {

        if (!Session::has('user')){
            $this->error('请登录');
            $this->redirect('admin/login/index');
        }

          $redis = Cache::store('redis')->handler();

           $user_id =  session('user');
          //获取资讯id
          $id = $request->get('id');
           //将收藏的资讯id存入到redis
          if ($redis->smembers('information_'.$user_id)== false){
              $this->error('你已收藏');
          }else{

              $redis->sadd('information_'.$user_id,$id);

              $this->success('收藏成功');
          }




    }
}
